//
//  HomeViewModel.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 16.03.25.
//

import Foundation
import SwiftUI

class HomeViewModel : KoiAccountingBaseViewModel {
    
    private let detailDao = KoiAccountingDB.standard.getDetailDao()
    private let budgetRepo = BudgetRepo()
    @Published var isLoading = false
    @Published var bookName: String = BookManager.standard.defaultBook().bookName.orEmpty
    @Published var bookColor: Color = BookManager.standard.defaultBook().getBookColor()
    @Published var overviewAreaData: OverviewAreaAccountingData = OverviewAreaAccountingData()
    @Published var detailRowGroupList: [AccountingDetailRowGroup] = Array()
    
    // 预算部分
    @Published var totalBudgetAmount: Double = 3000
    // 已支出
    @Published var expenseAmount: Double = 3000
    // 已使用百分比
    @Published var usePercent = 0.3
    // 剩余预算
    @Published var surplusAmount: Double = 1000
    
    @Published var deleteState: String = ""
    
    func initData() {
        if (KoiAccountingUserManager.standard.isNeedInit()) {
            initDefaultData()
        }
        loadData()
    }
    
    func loadData(month: String = Date().toYearMonth()) {
        getOverviewAccountingData(month: month)
        getDetailList(month: month)
        getBudgetOverview(month: month)
    }
    
    func getDetailList(month: String) {
        DispatchQueue.global(qos: .background).async {
            let result = self.detailDao.getAccountDetailListByMonth(month: month, uid: self.uid, bookId: self.bookId)
            DispatchQueue.main.async {
                self.detailRowGroupList = result
            }
        }
    }
    
    /**
     初始化默认数据
     */
    func initDefaultData() {
        // 通知服务端改变 need init 状态
        self.isLoading = true
        DispatchQueue.global(qos: .background).async {
            KoiAccountingData.initDefaultData()
            DispatchQueue.main.async {
                // 初始化数据完成，取消 loading 状态
                self.isLoading = false
            }
        }
    }
    
    func initBook() {
        
    }
    
    func clearDefaultData() {
        self.isLoading = true
        DispatchQueue.global(qos: .background).async {
            KoiAccountingData.clearDefaultData()
            DispatchQueue.main.async {
                self.isLoading = false
            }
        }
    }
    
    /**
     月支出收入结余数据
     @ month 格式 yyyy-MM
     */
    func getOverviewAccountingData(month: String) {
        print("getOverviewAccountingData query month %@", month)
        DispatchQueue.global(qos: .background).async {
            let result = self.detailDao.getOverviewAccountingData(month: month, uid: self.uid, bookId: self.bookId)
            DispatchQueue.main.async {
                self.overviewAreaData = result ?? OverviewAreaAccountingData()
            }
        }
    }
    
    func getBudgetOverview(month: String = Date().toYearMonth()) {
        asyncBackground {
            let result = self.budgetRepo.getBudgetTotal(month: month, uid: self.uid, bookId: self.bookId)
            self.asyncMain {
                self.totalBudgetAmount = result.budgetAmount
                if result.budgetAmount == 0 {
                    self.usePercent = 0
                    self.surplusAmount = 0
                    self.expenseAmount = 0
                } else {
                    self.usePercent = result.expenseAmount / result.budgetAmount
                    self.surplusAmount = result.surplusAmount
                    self.expenseAmount = result.expenseAmount
                }
                
            }
        }
    }
    
    func getAccountDetailByMonthGroupByDay(month:String) {
        DispatchQueue.global(qos: .background).async {
            let result = self.detailDao.getAccountDetailListByMonth(month: month, uid: self.uid, bookId: self.bookId)
            DispatchQueue.main.async {
                self.detailRowGroupList = result
            }
        }
    }
    
    func delete(detail: AccountingDetailCombine?) {
        guard let detail = detail else { return }
        asyncBackground {
            self.detailDao.delete(recordId: detail.detail.recordId, uid: self.uid, bookId: self.bookId)
            self.asyncMain {
                self.deleteState = "success"
            }
        }
    }
}
